package com.example.springbootflowabledemo.service.impl.sys;


import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springbootflowabledemo.domian.pojo.sys.SysDept;
import com.example.springbootflowabledemo.domian.pojo.sys.SysUser;
import com.example.springbootflowabledemo.domian.pojo.sys.SysUserDept;
import com.example.springbootflowabledemo.domian.vo.DeptVo;
import com.example.springbootflowabledemo.domian.vo.UserVo;
import com.example.springbootflowabledemo.exception.ServiceException;
import com.example.springbootflowabledemo.mapper.sys.SysDeptMapper;
import com.example.springbootflowabledemo.mapper.sys.SysUserDeptMapper;
import com.example.springbootflowabledemo.mapper.sys.SysUserMapper;
import com.example.springbootflowabledemo.service.sys.SysDeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@DS("sys")
@Service
@Transactional(rollbackFor = Exception.class)
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    @Autowired
    private SysUserDeptMapper sysUserDeptMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public void addDept(SysDept sysDept) {
        log.info("新增部门dept={}", sysDept);
        if (sysDept.getParentId() != null) {
            SysDept parentDept = this.getById(sysDept.getParentId());
            String path;
            if (parentDept.getParentId() == null) {
                path = parentDept.getId() + "|";
            } else {
                path = parentDept.getPath() + parentDept.getId() + "|";
            }
            sysDept.setPath(path);
        }
        this.save(sysDept);
    }

    @Override
    public void deleteDept(Long id) {
        log.info("删除部门id={}", id);
        if (id == null) {
            throw new ServiceException("ID IS NULL");
        }
        List<SysDept> depts = this.lambdaQuery()
                .eq(SysDept::getParentId, id)
                .list();

        if (CollectionUtils.isNotEmpty(depts)) {
            throw new ServiceException("非叶子节点无法删除");
        }
        this.removeById(id);
    }

    @Override
    public List<SysDept> getDeptByParentId(Long parentId) {
        log.info("根据父ID查询部门 parentId={}", parentId);
        return this.lambdaQuery()
                .select(SysDept::getId, SysDept::getName)
                .eq(parentId != null, SysDept::getParentId, parentId)
                .isNull(parentId == null, SysDept::getParentId)
                .list();
    }

    @Override
    public List<DeptVo> getDeptWithUser(Long parentId) {
        log.info("查询部门以及下的用户parentId={}", parentId);

        List<SysDept> sysDepts = getDeptByParentId(parentId);
        if (CollectionUtils.isEmpty(sysDepts)) {
            return new ArrayList<>();
        }

        List<DeptVo> deptVos = new ArrayList<>();
        for (SysDept dept : sysDepts) {
            DeptVo deptVo = new DeptVo();
            deptVo.setDeptId(dept.getId());
            deptVo.setDeptName(dept.getName());
            deptVos.add(deptVo);
            List<SysUserDept> sysUserDepts = sysUserDeptMapper.selectList(
                    new QueryWrapper<SysUserDept>()
                            .lambda()
                            .eq(SysUserDept::getDeptId, dept.getId())
            );
            if (CollectionUtils.isEmpty(sysUserDepts)) {
                continue;
            }

            //获取部门下的user信息
            deptVo.setUsers(getUserVos(sysUserDepts.stream().map(SysUserDept::getUserId).collect(Collectors.toList())));
        }
        return deptVos;
    }

    /**
     * 获取user信息
     *
     * @param userIds
     * @return
     */
    private List<UserVo> getUserVos(List<Long> userIds) {
        List<SysUser> sysUsers = sysUserMapper.selectList(
                new QueryWrapper<SysUser>()
                        .lambda()
                        .in(SysUser::getId, userIds)
        );
        if (CollectionUtils.isEmpty(sysUsers)) {
            return new ArrayList<>();
        }
        List<UserVo> userVos = new ArrayList<>();
        for (SysUser sysUser : sysUsers) {
            UserVo userVo = new UserVo();
            userVo.setUserId(sysUser.getId());
            userVo.setNickname(sysUser.getNickname());
            userVo.setUsername(sysUser.getUsername());
            userVos.add(userVo);
        }
        return userVos;
    }
}
